<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="filters">
            <el-form-item prop="appointCode">
              <el-input v-model="filters.appointCode" clearable placeholder="预约号"></el-input>
            </el-form-item>
            <el-form-item prop="itemName">
              <el-input v-model="filters.itemName" clearable placeholder="预约项目"></el-input>
            </el-form-item>
            <el-form-item prop="patientName">
              <el-input v-model="filters.patientName" clearable placeholder="患者姓名"></el-input>
            </el-form-item>
            <el-form-item prop="appointState">
              <el-select v-model="filters.appointState" :clearable="true" placeholder="预约状态">
                <el-option v-for="item in appointStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="printState">
              <el-select v-model="filters.printState" :clearable="true" placeholder="结果打印状态">
                <el-option v-for="item in agenciesStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item prop="hospitalId" v-if="userRole!=2">
              <el-select v-model="filters.hospitalId" :clearable="true" filterable :filter-method="listHospital" placeholder="请选择医院">
                <el-option
                  v-for="item in hospitalList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>-->
            <HospitalSelect @hospitalId="getHospitalId" :site="2" v-if="userRole == 1"></HospitalSelect>
            <InstitutionSelect @institutionId="getInstitutionId" :site="2" v-if="userRole == 1"></InstitutionSelect>
            <el-form-item prop="state" v-has="permissionExport">
              <el-select v-model="filters.state" :clearable="true" placeholder="状态">
                <el-option key="1" label="正常" value="1"></el-option>
                <el-option key="-1" label="已删除" value="-1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="dateType">
              <el-select v-model="filters.dateType" :clearable="true" placeholder="日期查询类型">
                <el-option v-for="item in dateTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="date">
              <el-date-picker
                v-model="filters.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                nd-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="init" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button size="mini" plain icon="el-icon-folder" type="info" v-has="permissionExport" @click="handleClickExport(0)">导出所有</el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder-opened" v-has="permissionExport" @click="handleClickExport(1)">合并导出</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table :data="appointList" v-loading="listLoading" element-loading-text="数据加载中，请稍后..." empty-text="对不起，没有找到相关数据！" fit highlight-current-row>
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="appointCode" label="预约号"></el-table-column>
        <el-table-column label="医院-科室-医生" width="240" v-if="userRole == 1">
          <template slot-scope="scope">
            <span>{{ scope.row.hospitalName }}-{{ scope.row.officeName }}-{{ scope.row.doctorName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医检-科室" width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.institutionName }}-{{ scope.row.insOfficeName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="预约项目" width="150"></el-table-column>
        <el-table-column prop="appointDate" :formatter="formatDate" label="预约日期" width="87"></el-table-column>
        <el-table-column prop="appointTime" label="时间" width="60"></el-table-column>
        <el-table-column width="120px" align="center" label="姓名-性别-年龄">
          <template slot-scope="scope">
            <span>{{ scope.row.patientName }} - {{ formatSex(scope.row.patientSex) }} - {{ scope.row.patientAge }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="patientCard" label="身份证" width="120"></el-table-column> -->
        <el-table-column prop="patientPhone" label="手机" width="120"></el-table-column>
        <el-table-column prop="appointEndTime" label="完成时间" width="87"></el-table-column>
        <!--<el-table-column width="80" label="操作记录" v-if="userRole == 1">
          <template slot-scope="scope">
            <el-popover ref="popover" placement="bottom-end" trigger="click"
                        :disabled="scope.$index !== modifyIndex">
              <appointRecords :recordList="appointRecordList" v-loading="scope.row.recordShow">
              </appointRecords>
              <el-button @click.stop="handleRecordClickNumber(scope.row, scope.$index)" slot="reference"
                         class="table-inline-name-button text-primary" type="text">
                {{ scope.row.recordCount || 0 }}次
              </el-button>
            </el-popover>
          </template>
        </el-table-column>-->
        <el-table-column prop="remark" label="预约备注" width="100"></el-table-column>
        <el-table-column width="100" align="center" label="预约/打印状态">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatAppointStates(scope.row.appointState)">{{ formatAppointState(scope.row.appointState) }}</el-tag>
              <el-tag size="mini" :type="formatPrintStates(scope.row.printState)">{{ formatPrintState(scope.row.printState) }}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建日期" width="87"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <!--<el-button v-has="permissionEdit" @click="handleClickEditor(scope.row)" size="mini">编辑</el-button>
            <el-button v-has="permissionUpStatus" @click="handleIsDisable(scope.row)" size="mini">删除</el-button>-->
            <el-button v-has="permissionPrint" v-if="scope.row.appointState === 20" @click="handleClickPrint(scope.row)" size="mini">打印预约单</el-button>
            <el-button v-has="permissionPrintReport" v-if="scope.row.appointState > 50" @click="handleClickPrintReport(scope.row, userRole)" size="mini"
              >{{ userRole === 2 ? '打印' : '预览' }}结果</el-button
            >
            <el-button v-has="permissionDownload" v-if="scope.row.appointState > 50" @click="handleClickDownload(scope.row)" size="mini">下载结果</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <!--<el-dropdown-item v-has="permissionCheck" @click.native="handleClickDetail(scope.row)">查看</el-dropdown-item>-->
                <el-dropdown-item v-has="permissionEdit" v-if="scope.row.appointState === 1 || scope.row.appointState === 50" @click.native="handleClickEditor(scope.row)"
                  >编辑</el-dropdown-item
                >
                <el-dropdown-item v-has="permissionUpdateTimes" v-if="scope.row.appointState === 10 && userRole !== 3" @click.native="handleClickUpdateTimes(scope.row)"
                  >修改时间</el-dropdown-item
                >
                <el-dropdown-item v-has="permissionUpdateRemark" v-if="userRole === 1" @click.native="handleClickUpdateRemark(scope.row)">修改备注</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpdateRemark" v-if="userRole === 1 && scope.row.appointState === 20" @click.native="handleClickResetAppointFile(scope.row)"
                  >重置预约单</el-dropdown-item
                >
                <el-dropdown-item v-has="permissionAgreeUpdate" v-if="scope.row.appointState === 50 && userRole !== 3" @click.native="handleClickAgreeUpdate(scope.row)"
                  >同意修改</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionAgreeCheck"
                  v-if="scope.row.appointState < 15 && scope.row.isAppointPay === 1 && userRole !== 2"
                  @click.native="handleClickAgreeCheck(scope.row)"
                  >审核通过</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionPayUpload"
                  v-if="scope.row.appointState === 15 && scope.row.isAppointPay === 1 && userRole !== 3"
                  @click.native="handleClickPayUpload(scope.row)"
                  >上传支付凭证</el-dropdown-item
                >
                <el-dropdown-item v-has="permissionExamineUpload" v-if="scope.row.appointState < 30 && userRole !== 2" @click.native="handleClickExamineUpload(scope.row)"
                  >心电诊断</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionSuccess"
                  v-if="scope.row.appointState === 1 && scope.row.isAppointPay !== 1 && userRole !== 2"
                  @click.native="handleClickSuccess(scope.row)"
                  >预约成功</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionSuccess"
                  v-if="scope.row.appointState === 16 && scope.row.isAppointPay === 1 && userRole !== 2"
                  @click.native="handleClickSuccess(scope.row)"
                  >预约成功</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionCancel"
                  v-if="(scope.row.appointState === 1 || scope.row.appointState === 15 || scope.row.appointState === 20) && userRole != 3"
                  @click.native="handleClickCancel(scope.row)"
                  >取消</el-dropdown-item
                >
                <el-dropdown-item
                  v-has="permissionAgreeCancel"
                  v-if="scope.row.appointState === 40 && (userRole === 1 || userRole === 3)"
                  @click.native="handleClickAgreeCancel(scope.row)"
                  >同意取消</el-dropdown-item
                >
                <el-dropdown-item v-has="permissionUploadReport" v-if="scope.row.appointState === 20 && userRole !== 2" @click.native="handleClickUploadReport(scope.row)"
                  >上传结果</el-dropdown-item
                >
                <el-dropdown-item v-has="permissionBackReport" v-if="scope.row.appointState > 50" @click.native="handleClickBackReport(scope.row)">撤回结果</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" v-if="scope.row.appointState === 30" @click.native="handleIsDisable(scope.row)">删除</el-dropdown-item>
                <!--<el-dropdown-item v-has="permissionPrint" v-if="scope.row.appointState === 2" @click.native="handleClickPrint(scope.row)">预览打印</el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickDownload(scope.row)">下载</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{scope.row.state == 0? '启用' : '禁用'}}</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <uploadFile ref="uploadFile" @uploadFileList="getUploadFileList" :accept="uploadAccept" folder="appoint"></uploadFile>
    <uploadAppointPay ref="uploadAppointPay"></uploadAppointPay>
    <AppointExamineMsg ref="appointExamineMsg" @refreshPage="refreshPage"></AppointExamineMsg>
    <viewPdf ref="viewPdf" :pdfUrl="pdfUrl" :isPrint="isPrint"></viewPdf>
    <Remarks ref="remarks" :remark="remarkForm.remark" @getRemark="updateRemark"></Remarks>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import uploadFile from '@/components/UploadFile';
import uploadAppointPay from '@/components/UploadAppointPay';
import AppointExamineMsg from '@/components/AppointExamineMsg';
import appointRecords from '@/components/AppointRecords';
import HospitalSelect from '@/components/HospitalSelect';
import InstitutionSelect from '@/components/InstitutionSelect';
import viewPdf from '@/components/viewPdf';
import * as constants from '@/constants/constants';
import axios from 'axios';
import Remarks from '@/components/Remarks';
import AppointApi from '@/api/appoint/appoint';
import AuthApi from '@/api/system/auth';
import { getStorage } from '@/utils/auth';
import * as stn from '@/constants/storeName';

export default {
  name: 'AppointManagement',
  inject: ['reload'], //注入局部刷新
  metaInfo: {
    meta: [{ httpEquiv: 'Content-Security-Policy', content: 'upgrade-insecure-requests' }],
  },
  data() {
    return {
      appointList: [],
      appointDataList: [],
      selectIds: [],
      userInfo: {},
      userRole: '',
      pdfUrl: '',
      appointId: 0,
      listLoading: true,
      isPrint: false,
      modifyIndex: '',
      appointRecordList: [],
      remarkForm: {
        id: null,
        remark: null,
      },
      filters: {
        appointCode: '',
        patientName: '',
        itemName: '',
        appointState: '',
        printState: '',
        hospitalId: '',
        institutionId: '',
        dateType: 1,
        state: '1',
        date: [],
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      uploadAccept: 'all',
      uploadData: {
        appointId: '',
        appointIdList: [],
        uploadFiles: [],
      },
      hospitalList: [],
      appointStatue: [
        { label: '预约中', value: 1 },
        { label: '协商中', value: 10 },
        { label: '预约成功', value: 20 },
        { label: '已取消', value: 30 },
        { label: '待确认取消', value: 40 },
        { label: '待确认修改', value: 50 },
        { label: '已上传结果', value: 60 },
      ],
      agenciesStatue: [
        { label: '未打印', value: 0 },
        { label: '已打印', value: 1 },
      ],
      dateTypeList: [
        { label: '创建日期', value: 1 },
        { label: '预约日期', value: 2 },
      ],

      permissionAdd: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_EDIT',
      permissionSuccess: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_SUCCESS',
      permissionAgreeCancel: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_AGREE_CANCEL',
      permissionAgreeUpdate: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_AGREE_UPDATE',
      permissionAgreeCheck: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_AGREE_CHECK',
      permissionPayUpload: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_PAY_UPLOAD',
      permissionExamineUpload: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_EXAMINE_UPLOAD',
      permissionUpdateTimes: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_UPDATE_TIMES',
      permissionUpdateRemark: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_UPDATE_REMARK',
      permissionCancel: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_CANCEL',
      permissionPrint: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_PRINT',
      permissionPrintReport: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_PRINT_REPORT',
      permissionDownload: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_DOWNLOAD_REPORT',
      permissionUploadReport: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_UPLOAD_REPORT',
      permissionBackReport: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_BACK_REPORT',
      permissionUpStatus: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_DELETE',
      permissionExport: 'SYSTEM_MANAGER_APPOINT_INFO_LIST_EXPORT',
      excelData: {},
      allList: [],
    };
  },
  components: {
    AppointExamineMsg,
    Remarks,
    uploadFile,
    viewPdf,
    appointRecords,
    HospitalSelect,
    InstitutionSelect,
    uploadAppointPay,
  },
  created() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  mounted() {
    // 为了实现手机端下拉框可以打字搜索
    this.$Utils.removeSelectReadOnly();
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listAppoint();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.listLoading = true;
      this.userInfo = getStorage(stn.USER_INFO);
      if (this.userInfo) {
        this.userRole = this.userInfo.userRole;
      }
      _this.initDate();
      // 从首页跳过来的
      let linkType = this.$route.query.linkType;
      if (linkType) {
        if (linkType === 1) {
          // 未打印预约单
          this.filters.appointState = 60;
          this.filters.printState = 0;
        } else if (linkType === 2) {
          // 今日新增预约单
          let begin = new Date();
          begin.setHours(0);
          begin.setMinutes(0);
          begin.setSeconds(0);
          let end = new Date();
          end.setHours(23);
          end.setMinutes(59);
          end.setSeconds(59);
          this.filters.date = [begin, end];
        } else if (linkType === 3) {
          // 待处理预约单（医检）
          this.filters.appointState = 1;
        }
      }
      //_this.listHospital();
      _this.listAppoint();
      this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },


    initDate() {
      let begin = new Date();
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      begin.setMonth(begin.getMonth() - 1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      this.filters.date = [begin, end];
    },
    resetForm() {
      this.$refs.filters.resetFields();
      this.initDate();
      this.onSearch();
    },
    formatSex(cellValue) {
      if (cellValue === 1) {
        return '男';
      } else if (cellValue === 2) {
        return '女';
      }
    },
    formatPrintState(cellValue) {
      if (cellValue === 0) {
        return '未打印';
      } else if (cellValue === 1) {
        return '已打印';
      }
    },
    formatPrintStates(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'danger';
      }
    },
    formatAppointState(cellValue) {
      if (cellValue === 1) {
        return '预约中';
      } else if (cellValue === 10) {
        return '协商中';
      } else if (cellValue === 15) {
        return '审核通过';
      } else if (cellValue === 16) {
        return '已上传支付凭证';
      } else if (cellValue === 20) {
        return '预约成功';
      } else if (cellValue === 30) {
        return '已取消';
      } else if (cellValue === 40) {
        return '待确认取消';
      } else if (cellValue === 50) {
        return '待确认修改';
      } else if (cellValue === 60) {
        return '已上传结果';
      }
    },
    formatAppointStates(cellValue) {
      if (cellValue === 1) {
        return '';
      } else if (cellValue === 10) {
        return '';
      } else if (cellValue === 20) {
        return 'success';
      } else if (cellValue === 30) {
        return 'info';
      } else if (cellValue === 40) {
        return 'warning';
      } else if (cellValue === 50) {
        return 'warning';
      } else if (cellValue === 60) {
        return 'success';
      }
    },
    formatState(row, column, cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      } else if (cellValue == 2) {
        return '待审核';
      }
    },
    formatDate(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, constants.FORMAT_DATE_YYYY_MM_DD);
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    // 产品导入
    getUploadFileList(val) {
      var _this = this;
      if (!val) {
        _this.$Utils.messageError('请选择pdf上传');
        return;
      }
      _this.uploadData.uploadFiles = val;
      if (_this.uploadData.appointId) {
        AppointApi.appointReportUpload(_this.uploadData).then((res) => {
          _this.$notify.success({
            title: message.TITLE_SUCCESS,
            message: message.MSG_UPLOAD_SUCCESS,
          });
          _this.listAppoint();
        });
      }
    },
    getHospitalId(val) {
      this.filters.hospitalId = val;
    },
    getInstitutionId(val) {
      this.filters.institutionId = val;
    },
    // 获取操作记录弹窗位于table的第几个
    handleRecordClickNumber(row, index) {
      this.modifyIndex = index;
      this.appointRecordList = [];
      this.$set(row, 'recordShow', true);
      let _this = this;
      AppointApi.listAppointRecord({ appointId: row.appointId }).then((res) => {
        this.$set(row, 'recordShow', false);
        if (res.data) {
          _this.appointRecordList = res.data;
        }
      });
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listAppoint();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listAppoint();
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/appoint/appointEdit',
        query: { id: row.appointId, itemId: row.itemId },
      });
    },
    handleClickAgreeCancel(row) {
      let _this = this;
      this.$confirm('是否同意医院取消该预约', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.updateAppointState({
          id: row.appointId,
          state: 40,
        }).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listAppoint();
        });
      });
    },
    handleClickUpdateTimes(row) {},
    handleClickUpdateRemark(row) {
      this.remarkForm.appointId = row.appointId;
      this.remarkForm.remark = row.remark;
      this.$refs.remarks.handleCreate();
    },
    handleClickResetAppointFile(row) {
      let _this = this;
      AppointApi.resetAppointFile({ appointId: row.appointId }).then((res) => {
        if (res.status == 0) {
          _this.$Utils.notifySuccess();
        } else {
          _this.$Utils.notifyError('重置失败，请稍后再试');
        }
      });
    },
    refreshPage(val) {
      this.listAppoint();
    },
    updateRemark(val) {
      let _this = this;
      _this.remarkForm.remark = val;
      AppointApi.updateAppoint(_this.remarkForm).then((res) => {
        _this.$Utils.notifySuccess();
        _this.listAppoint();
      });
    },
    handleClickAgreeUpdate(row) {
      let _this = this;
      this.$confirm('是否同意医检机构修改该预约', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.updateAppointState({
          id: row.appointId,
          state: 50,
        }).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listAppoint();
        });
      });
    },
    handleClickAgreeCheck(row) {
      let _this = this;
      _this.$confirm('确定该预约审核通过吗？', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.updateAppointState({
          id: row.appointId,
          state: 15,
        }).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listAppoint();
        });
      });
    },
    handleClickPayUpload(row) {
      let _this = this;
      _this.$refs.uploadAppointPay.handleCreate(row.appointId);
    },
    handleClickExamineUpload(row) {
      let _this = this;
      if (_this.userInfo.userId) {
        AuthApi.getAdminInfo({ userId: _this.userInfo.userId }).then((res) => {
          if (!res.data.signUrl) {
            _this.$Utils.notifyWarn('请点击右上角登录名上传电子签名，详情可咨询客服热线');
          } else {
            _this.$refs.appointExamineMsg.handleCreate(row.appointId);
          }
        });
      }
    },
    handleClickSuccess(row) {
      let _this = this;
      this.$confirm('是否通过该预约申请', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.updateAppointState({
          id: row.appointId,
          state: 20,
        }).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listAppoint();
        });
      });
    },
    handleClickCancel(row) {
      let _this = this;
      this.$confirm('是否取消该预约申请', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.updateAppointState({
          id: row.appointId,
          state: 30,
        }).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listAppoint();
        });
      });
    },
    handleClickPrint(row) {
      let _this = this;
      AppointApi.getAppointInfo({ appointId: row.appointId })
        .then((res) => {
          if (res.data.appointFileUrl) {
            _this.isPrint = false;
            _this.pdfUrl = res.data.appointFileUrl;
            this.$refs.viewPdf.handleCreate();
            //_this.$OpenUrl(res.data.appointFileUrl);
            //window.open(res.data.appointFileUrl, 'PDF', 'left=100, left=300, width=900, height=700')
          } else {
            _this.$Utils.notifyError('预约单暂未生成，请稍后再试');
          }
        })
        .catch((error) => {
          _this.$Utils.notifyError('打印失败，请稍后重试');
        });
    },
    handleClickUploadReport(row) {
      // 上传结果
      let _this = this;
      _this.uploadAccept = 'pdf';
      _this.uploadData.appointId = row.appointId;
      _this.uploadData.appointIdList = [];
      _this.$refs.uploadFile.handleCreate();
    },
    handleClickBackReport(row) {
      let _this = this;
      this.$confirm('是否撤回已上传的结果', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.appointReportBack({
          appointId: row.appointId,
        }).then((res) => {
          _this.listAppoint();
        });
      });
    },
    handleClickForPrint() {
      let _this = this;
      if (_this.isPrint) {
        _this.$confirm('是否已打印预约单结果', message.TITLE_PROMPT, { cancelButtonText: '取消', confirmButtonText: '确定' }).then(() => {
          let param;
          if (_this.appointId > 0) {
            param = { appointId: _this.appointId };
          } else {
            /*if(_this.selectIds.length > 0){
                param = {reportIds:_this.selectIds.toString()}
              }*/
          }
          AppointApi.appointReportPrint(param).then((res) => {
            //console.log("打印成功")
          });
        });
      }
    },
    handleClickPrintReport(row, role) {
      let _this = this;
      AppointApi.getAppointInfo({ appointId: row.appointId })
        .then((res) => {
          if (res.data.reportFileUrl) {
            if (role === 2) {
              // 医生打印，机构预览
              _this.isPrint = true;
              _this.appointId = row.appointId;
            } else {
              _this.isPrint = false;
            }
            _this.pdfUrl = res.data.reportFileUrl;
            this.$refs.viewPdf.handleCreate();
          } else {
            _this.$Utils.notifyError('结果暂未生成，请稍后再试');
          }
        })
        .catch((error) => {
          _this.$Utils.notifyError('打印失败，请稍后重试');
        });
    },
    handleClickDownload(row) {
      let _this = this;
      let url = process.env.BASE_API + constants.appointReportDown + '?appointId=' + row.appointId;
      axios
        .get(url, {
          //url: 接口地址
          responseType: `arraybuffer`, //一定要写
        })
        .then((res) => {
          if (res.status == 200) {
            let blob = new Blob([res.data], {
              //type: `application/msword` //word文档为msword,pdf文档为pdf
              type: `application/pdf`, //word文档为msword,pdf文档为pdf
            });
            let objectUrl = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            let fName = row.patientName + row.appointCode; //下载文件的名字
            link.href = objectUrl;
            //link.setAttribute("download", fName);
            link.download = fName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(objectUrl); // 释放掉blob对象
          } else {
            _this.$Utils.notifyError('下载失败，请稍后重试');
          }
        });
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        //console.log(JSON.stringify(val[i]))
        let id = val[i].appointId;
        this.selectIds.push(id);
      }
    },
    handleIsDisable(row) {
      let _this = this;
      this.$confirm('是否删除该预约信息', message.TITLE_PROMPT, {}).then(() => {
        AppointApi.deleteAppoint({
          appointId: row.appointId,
          state: -1,
        }).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listAppoint();
        });
      });
    },
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/appoint/appointAdd');
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/appoint/appointDetail',
        query: { id: row.appointId },
      });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listAppoint();
    },
    listAppoint() {
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
        appointCode: _this.filters.appointCode,
        patientName: _this.filters.patientName,
        appointState: _this.filters.appointState,
        printState: _this.filters.printState,
        hospitalId: _this.filters.hospitalId,
        institutionId: _this.filters.institutionId,
        itemName: _this.filters.itemName,
        state: _this.filters.state,
        dateType: _this.filters.dateType,
      };
      if (this.filters.date && this.filters.date.length == 2) {
        cond.createDateBegin = this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
        cond.createDateEnd = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
      }
      AppointApi.listAppoint(cond)
        .then((res) => {
          _this.appointList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.listLoading = false;
        })
        .catch((error) => {
          _this.listLoading = false;
          console.error(error);
        });
    },
    handleClickExport(groupBy) {
      let _this = this;
      this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let cond = {
            groupBy: groupBy,
            appointCode: _this.filters.appointCode,
            patientName: _this.filters.patientName,
            appointState: _this.filters.appointState,
            printState: _this.filters.printState,
            hospitalId: _this.filters.hospitalId,
            institutionId: _this.filters.institutionId,
            itemName: _this.filters.itemName,
            dateType: _this.filters.dateType,
            state: _this.filters.state,
            pageNo: 1,
            pageSize: 10000,
          };
          if (this.filters.date && this.filters.date.length == 2) {
            cond.createDateBegin = this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
            cond.createDateEnd = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
          }
          AppointApi.listAppoint(cond)
            .then((res) => {
              if (res.data.list && res.data.list.length > 0) {
                let result = res.data.list;
                result.forEach((item) => {
                  if (item.patientSex) {
                    if (item.patientSex === 1) {
                      item.patientSexName = '男';
                    } else if (item.patientSex === 2) {
                      item.patientSexName = '女';
                    }
                  }
                  item.appointStateName = this.formatAppointState(item.appointState);
                });
                _this.excelData = result;
                this.export2Excel();
              } else {
                _this.$Utils.notifyError('未找到可导出的数据，请重新查询');
              }
            })
            .catch((error) => {
              console.error(error);
            });
        })
        .catch(() => {
          console.error(error);
        });
    },
    export2Excel() {
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel'); //这里必须使用绝对路径
        //时间，姓名，项目，预约号，预约单位，医检单位，点击通过的账号
        let tHeader = [
          '预约号',
          '预约日期',
          '时间段',
          '患者姓名',
          '患者性别',
          '患者年龄',
          '项目名称',
          '预约单位',
          '预约科室',
          '预约医生',
          '预约备注',
          '医检单位',
          '审核通过人',
          '预约状态',
          '创建日期',
        ]; // 导出的表头名
        let filterVal = [
          'appointCode',
          'appointDate',
          'appointTime',
          'patientName',
          'patientSexName',
          'patientAge',
          'itemName',
          'hospitalName',
          'officeName',
          'doctorName',
          'remark',
          'institutionName',
          'passUserName',
          'appointStateName',
          'createDate',
        ]; // 导出的表头字段名
        if (this.userRole == 3) {
          this.$delete(tHeader, 5);
          this.$delete(filterVal, 5);
        }
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        //let time1,time2 = '';
        //export_json_to_excel(tHeader, data, `[${time1}-${time2}]医生管理列表`);// 导出的表格名称，根据需要自己命名
        let currentTime = this.$Utils.formatDate(new Date(), 'yyyy-MM-dd');
        export_json_to_excel(tHeader, data, `康来预约单数据_${currentTime}`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
